const db = require('../db/index.js')
const bcrypt = require('bcryptjs')
const { log } = require('debug/src/browser.js')
const code = require('jade/lib/nodes/code.js')
const jwt = require('jsonwebtoken')
const fs = require('fs');
const axios = require('axios');

//注册用户
const register = async (req, res) => {
    const { username, password, email } = req.body
    // 检查用户名是否已存在
    const [existingUser] = await db.query('select * from Users where username = ?', [username])
    if (existingUser.length > 0 && existingUser[0].username === username) {
        return res.cc({
            code: 400,
            message: '用户名已存在，请重新注册！'
        })
    }
    // 检查必填字段
    if (!username || !password) {
        return res.cc({
            code: 400,
            message: '用户名和密码不能为空'
        })
    }
    //检查用户名和密码格式
    if (username.length < 3 || username.length > 15) {
        return res.cc({
            code: 400,
            message: '用户名长度必须在3-15个字符之间'
        })
    }
    const passwordReg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{6,}$/
    if (!passwordReg.test(password)) {
        return res.cc({
            code: 400,
            message: '密码必须包含大小写字母和数字'
        })
    }
    //检查邮箱格式
    const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailReg.test(email)) {
        return res.cc({
            code: 400,
            message: '邮箱格式不正确'
        })
    } else {
        // 检查邮箱是否已存在
        const [emailRows] = await db.query('select * from Users where email = ?', [email]);
        if (emailRows.length > 0) {
            return res.cc({
                code: 400,
                message: '邮箱已被注册，请更换邮箱！'
            });
        }
    }

    //加密密码
    const salt = await bcrypt.genSalt(10)
    const hashPassword = await bcrypt.hash(password, salt)
    await db.query('insert into Users (username, password_hash, email) values (?,?,?)', [username, hashPassword, email])
    return res.cc({
        code: 200,
        message: '注册成功！'
    })
}

//登录
const login = async (req, res) => {
    const { username, password } = req.body
    //检查必填字段
    if (!username || !password) {
        return res.cc({
            code: 400,
            message: '用户名和密码不能为空'
        })
    }

    //检查用户名是否存在
    const [user] = await db.query('select * from Users where username = ?', username)
    if (user.length === 0 || !user) {
        return res.cc({
            code: 400,
            message: '用户名不存在!请先注册！'
        })
    } else {
        //校验密码
        const passwordValid = await bcrypt.compare(password, user[0].password_hash)
        if (!passwordValid) {
            return res.cc({
                code: 400,
                message: '密码错误！'
            })
        } else {
            // 登录成功，不再生成 token
            return res.send({
                code: 200,
                message: '登录成功！',
                username: user[0].username,
                user_id: user[0].id
            })
        }
    }
}

//获取用户已投递的岗位
const getPosition = async (req, res) => {
    const { user_id } = req.query

    if (!user_id) {
        return res.cc({
            code: 400,
            message: '用户ID不能为空'
        });
    }
    const [position] = await db.query('select * from InterviewSessions where user_id = ?', user_id)
    console.log("position:", position);

    return res.send({
        code: 200,
        message: '获取成功！',
        data: position,
    })
}


// 获取已经上传的岗位
const Positions = async (req, res) => {
    console.log("req.body:", req.body);

    const { user_id } = req.body
    if (!user_id) {
        return res.cc({
            code: 400,
            message: '用户ID不能为空'
        });
    }
    const [position] = await db.query('select * from CompanyDocuments where user_id = ?', user_id)
    console.log("position:", position);

    return res.send({
        code: 200,
        message: '获取成功！',
        data: position,
    })
}


//获取岗位详情
const getCompanyDetail = async (req, res) => {
    const { company_id } = req.query;
    console.log(company_id);

    const [companyDetail] = await db.query('select * from CompanyDocuments where id = ?', [company_id])
    return res.send({
        code: 200,
        message: '获取成功！',
        data: companyDetail,
    })
}

// 返回时间，分数和公司名称(面试复盘)
const MyScore = async (req, res) => {
    const { user_id } = req.query;
    console.log(user_id);

    const [sessions] = await db.query('select * from InterviewSessions where user_id = ?', [user_id]);
    if (!sessions.length) {
        return res.send({ code: 404, message: '没有面试记录' });
    }

    // 用 Promise.all 并发查公司信息和分数
    const results = await Promise.all(sessions.map(async session => {
        const [company] = await db.query('select * from CompanyDocuments where id = ?', [session.company_id]);
        const [score] = await db.query('select * from Evaluations where session_id = ?', [session.id]);
        return {
            company: company[0] || null,
            start_time: session.start_time,
            score: score[0] || null
        };
    }));

    return res.send({
        code: 200,
        message: '获取成功！',
        data: results
    });
}


module.exports = {
    register,
    login,
    getPosition,
    getCompanyDetail,
    Positions,
    MyScore
}